package cn.itcast.usermanage.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import cn.itcast.usermanage.pojo.User;
import cn.itcast.usermanage.service.AutoUserService;

@RestController
@RequestMapping("/rest")
public class RestUserController {


	@Autowired
	private AutoUserService userService;
	/**
	 * 根据ID查询用户
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping(value = "{id}")
	public ResponseEntity<User> queryUserById(@PathVariable("id") Long id) {
		try {
			// 查询用户
			User user = this.userService.queryUserById(id);
			if (user != null) {
				// 资源存在，返回200
				return new ResponseEntity<>(user, HttpStatus.OK);
			}
			// 资源不存在，返回404
			return new ResponseEntity<>(HttpStatus.NOT_FOUND);
		} catch (Exception e) {
			e.printStackTrace();
			// 出现异常，返回500
			return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}
	
	/**
	 * 新增用户
	 * @param user
	 * @return
	 */
	@RequestMapping(method=RequestMethod.POST)
	public ResponseEntity<Void> saveUser(User user){
		try {
			// 新增用户
			this.userService.saveUser(user);;
			// 新增成功，返回201
			return new ResponseEntity<Void>(HttpStatus.CREATED);
		} catch (Exception e) {
			e.printStackTrace();
			// 出现异常，返回500 
			return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

	/**
	 * 修改用户
	 * @param user
	 * @return
	 */
	@RequestMapping(method=RequestMethod.PUT)
	public ResponseEntity<Void> updateUser(User user){
		try {
			// 修改用户
			this.userService.updateUser(user);
			// 成功，返回204 ,操作成功，但是不返回数据
			return new ResponseEntity<Void>(HttpStatus.NO_CONTENT);
		} catch (Exception e) {
			e.printStackTrace();
			// 出现异常，返回500
			return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

	/**
	 * 删除用户
	 * @param user
	 * @return
	 */
	@RequestMapping(method=RequestMethod.DELETE)
	public ResponseEntity<Void> deleteUser(@RequestParam("ids")Long[] ids){
		try {
			// 删除用户
			this.userService.deleteUserByIds(ids);
			// 成功，返回204 ,操作成功，但是不返回数据
			return new ResponseEntity<Void>(HttpStatus.NO_CONTENT);
		} catch (Exception e) {
			e.printStackTrace();
			// 出现异常，返回500
			return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}

}
